import api from '@/api/user'
import router from '@/router'
import moment from 'moment';
import { Message } from 'element-ui';

//user模块全局化 
// state.user mapMutations({CartCount: 'user/XXX'})  mapActions({fetchCartCount: 'user/XXXX'}), commit('user/XXXX')
const user = {
    namespaced: true,
  
    state: {
        login: false,
        userInfo: {
        },
        codeError: '',
        cartNum: 0,
        mesNum: 0,
        orderNum: {
            DoneCount: 0,
            UnDoneCount: 0 
        },
        actMessage: [],
        allActMessage: [],
        detailPagination: {
            total:  null, //总共有几个
            pageNum: 1, //当前页数
            pageSize: 9, //一个展示几个
        },
        realData: {
            user_realName: null,
            user_idNumber: null,
            user_bankCard: null
        },
        reload: false,
        myTrade: [],
        active: 0,
        self_password: '',
    },

    mutations: {
        //userInfo取的是localStorage的userInfo 退出时清空
        saveUser: (state, { roleid, shopid, Users: User }) => {
            //注入userInfo
            state.login = true;
            let storage = window.localStorage;
            state.realData = {
                user_realName: User.user_realName,
                user_idNumber: User.user_idNumber,
                user_bankCard: User.user_bankCard
            };
            
            User.user_regTime = moment(User.user_regTime).format('YYYY-MM-DD HH:mm:ss')
            User.shop_id = shopid !== '用户暂未开铺' ? shopid : '';
            User.user_restMoney = Number(User.user_restMoney).toFixed(2);
            //localStorage数据 加密
            storage.userInfo = JSON.stringify(Object.assign(User,{
                user_realName: User.user_realName ? 1 : '',
                user_idNumber: User.user_idNumber ? 1 : '',
                user_bankCard: User.user_bankCard ? 1 : ''
            }));
            //页面显示的数据
            state.userInfo = Object.assign({},JSON.parse(storage.userInfo), state.realData);
            //存入页面state
        },
        //首页调用 用户没有退出的话 继续保持登录状态
        getLocalStorage: (state, realData) => {
            let storage = window.localStorage;
            state.login = true;
            if(storage.userInfo){
                state.userInfo = Object.assign({},JSON.parse(storage.userInfo), realData);
            }
        },
        //点击退出 清掉storage中的userInfo
        deleteLocalStorage: (state) => {
            let storage = window.localStorage;
            storage.removeItem('userInfo');
            storage.removeItem('password');
            state.login = false;
        },
        setError: (state, mes) => {
            state.codeError = mes;
        },
        saveCartNum: (state, cartNum) => {
            state.cartNum += cartNum;
        },
        saveMesCount: (state, mesNum) => {
            state.mesNum += mesNum;
            if(state.mesNum < 0){
                state.mesNum = 0;
            }
        },
        saveOrderCount: (state, orderNum) => {
            state.orderNum = Object.assign(state.orderNum,orderNum);
            if(state.orderNum < 0){
                state.orderNum = 0;
            }
        },
        saveMyUserReal: (state, realResult) => {
            let storage = window.localStorage;
            storage.removeItem('userInfo');
            // 隐藏一下信息
            if(realResult.shop_id){
                storage.userInfo = JSON.stringify(Object.assign(state.userInfo, { shop_id: realResult.shop_id })); 
            }else{
                storage.userInfo = JSON.stringify(Object.assign(state.userInfo, { user_bankCard: 1, user_idNumber: 1, user_realName: realResult.user_realName })); 
            }
            storage.userInfo = JSON.stringify(Object.assign(state.userInfo, { user_bankCard: 1, user_idNumber: 1, user_realName: realResult.user_realName }));
            state.userInfo = Object.assign(state.userInfo, realResult);
        },
        saveActMessage: (state, list) => {
            state.actMessage.splice(0, state.actMessage.length);
            state.allActMessage.splice(0, state.actMessage.length);
            list.forEach((item,index) => {
                item.key = index;
                item.message_createTime = moment(item.message_createTime).format('YYYY-MM-DD HH:mm:ss');
            })
            state.actMessage = [...list].splice(0,8);

            state.allActMessage = [...list];
        },
        saveMyTrade: (state, { list, detailPagination }) => {
            state.myTrade.splice(0,state.myTrade.length);
            list.forEach(item => {
                item.act_createTime = moment(item.act_createTime).format('YYYY-MM-DD HH:mm:ss');
            })
            state.myTrade = [...list];
            state.detailPagination = Object.assign(state.detailPagination ,detailPagination);
            state.reload = true;
        },
        changeReload: (state, reload) => {
            state.reload = reload;
        },
        changeActive: (state, active) => {
            state.active = active;
            if (state.active === 2) state.active = state.active + 1;
        },
        changeUsertotalPay: (state, num) => {
            state.userInfo = Object.assign(state.userInfo, { user_totalPay: Number(Number(state.userInfo.user_totalPay) + num).toFixed(2) });
            let temp = localStorage.userInfo ? JSON.parse(localStorage.userInfo) : null;
            localStorage.removeItem('userInfo');

            let ctemp = Object.assign(temp, { user_totalPay: Number(Number(temp.user_totalPay) + num).toFixed(2) });
            localStorage.userInfo = JSON.stringify(ctemp);

        },
        changeUserrestMoney: (state, num) => {
            state.userInfo = Object.assign(state.userInfo, { user_restMoney: Number(Number(state.userInfo.user_restMoney) + num).toFixed(2) });
            let temp = localStorage.userInfo ? JSON.parse(localStorage.userInfo) : null;
            localStorage.removeItem('userInfo');
            let ctemp = Object.assign(temp, { user_restMoney: Number(Number(temp.user_restMoney) + num).toFixed(2) });
            localStorage.userInfo = JSON.stringify(ctemp);
        },
        saveMyRecharge: (state, money) => {
            let storage = window.localStorage;
            storage.removeItem('userInfo');

            let user_restMoney = Number(Number( state.userInfo.user_restMoney ) + Number( money )).toFixed(2);
            state.userInfo = Object.assign(state.userInfo, { user_restMoney });
            storage.userInfo = JSON.stringify(state.userInfo);

        },
        savePassword: (state, password) => {
            localStorage.setItem('password', password);
        },
        saveNewPic: (state, picAdd) => {
            state.userInfo.user_pic = picAdd;
        }
    },

    actions:{
        async fetchLogin({ commit },payload) {
            const { code, extend } = await api.shirologin(payload);
            if(code === 200){
                commit('saveUser',extend.result);
                commit('savePassword', payload.user_password);
                router.push({ name: 'Index' });
                Message({
                    type: 'success',
                    message: '登录成功。',
                    showClose: true
                });
            }else if(code === 100){
                commit('setError', extend.info);
                Message({
                    type: 'error',
                    message: '登录失败,请重试。',
                    showClose: true
                });
            }
        },
        //验证码
        fetchValidateCode({ commit },payload) {
            return api.validateCode(payload);
        },
        //个人信息 只用于拿去认证信息
        async fetchDetailById({ commit },payload) {
            const { code, extend: { result:{ Users: List } } } = await api.DetailById(payload);
            const realData = {
                user_realName: List[0].user_realName,
                user_idNumber: List[0].user_idNumber,
                user_bankCard: List[0].user_bankCard
            };
            if(code === 200){
                commit('getLocalStorage',realData);
                commit('saveNewPic', List[0].user_pic);
            }else{
                return ;
            }
        },
        //注册
        async fetchRegister({ commit },payload) {
            const { code } = await api.userRegister(payload);
            if(code === 200){
                commit('changeActive',2);
                Message({
                    type: 'success',
                    message: '注册成功!',
                    showClose: true
                });
            }else{
                Message({
                    type: 'error',
                    message: '注册失败,请重试。',
                    showClose: true
                });
                return ;
            }
        },
        //检查用户名是否重复
        fetchCheckUser({ commit },payload) {
            return api.checkUser(payload);
        },
        async fetchCartCount({ commit },payload) {
            const { code, extend: { result: { count } } } = await api.getCartCount(payload);
            if(code === 200){
                commit('saveCartNum',count);
            }
        },
        async fetchMessageCount({ commit },payload) {
            const { code, extend: { result: { count } } } = await api.getMessageCount(payload);
            if(code === 200){
                commit('saveMesCount', count);
            }
        },
        //个人充值
        async fetchRecharge({ commit },payload) {
            const { code } = await api.recharge(payload);
            if(code === 200){
                commit('saveMyRecharge', payload.recharge);
                Message({
                    type: 'success',
                    message: '充值成功,快去购买心仪的宝贝吧。',
                    showClose: true
                });
            }else{
                Message({
                    type: 'error',
                    message: '充值失败,请重试!',
                    showClose: true
                });
            }
        },
        //个人提现
        async fetchCash({ commit },payload) {
            const { code } = await api.cash(payload);
            if(code === 200){
                commit('saveMyRecharge', -payload.cash);
                Message({
                    type: 'success',
                    message: '提现成功。',
                    showClose: true
                });
            }else{
                Message({
                    type: 'error',
                    message: '提现失败,请重试!',
                    showClose: true
                });
            }
        },
        //活动信息显示
        async fetchActMessages({ commit },payload) {
            const { code, extend: { List } } = await api.actMessages(payload);
            if(code === 200){
                commit('saveActMessage',List);
            }
        },
        //查看个人明细记录
        async fetchGetDetail({ commit },payload) {
            const { code, extend: { pageInfo } } = await api.getDetail(payload);
            if(code === 200){
                commit('changeReload',false);
                commit('saveMyTrade', { 
                    list: pageInfo.list, 
                    detailPagination: {
                        total:  pageInfo.total, //总共有几个
                        pageNum: pageInfo.pageNum, //当前页数
                        pageSize: pageInfo.pageSize, //一个展示几个
                    }
                });
            }
        },
        //订单数量
        async fetchOrderCount({ commit },payload) {
            const { code, extend: { OrderCountResult } } = await api.OrderCount(payload);
            if(code === 200){
                commit('saveOrderCount', OrderCountResult);
            }
        },
        //实名认证
        async fetchDoReal({ commit },payload) {
            const { code } = await api.doReal(payload);
            if(code === 200){
                commit('saveMyUserReal',payload);
                Message({
                    type: 'success',
                    message: '认证成功。',
                    showClose: true
                });
            }else{
                Message({
                    type: 'error',
                    message: '认证失败,请重试。',
                    showClose: true
                });
            }
        },
        //开店
        async fetchOpenShop({ commit },payload) {
            const { code } = await api.openShop(payload);
            if(code === 200){
                commit('saveMyUserReal',payload);  
                const { code: code2, extend: { result:{ shopid } } }= await api.DetailById({ user_id: payload.user_id });
                if(code2 === 200){
                    commit('saveMyUserReal',{ shop_id : shopid});
                    router.push({
                        name: 'Shop',
                        query: { shop_id: shopid }
                    });
                }
                Message({
                    type: 'success',
                    message: '提交成功,请等待审核....',
                    showClose: true
                });
            }else{
                Message({
                    type: 'error',
                    message: '提交失败,请重试。',
                    showClose: true
                });
            }
        },
        //修改密码
        async fetchUpdatePassword({ commit },payload) {
            const { code } = await api.updatePassword(payload);
            if(code === 200){
                commit('savePassword', payload.user_password);
                Message({
                    type: 'success',
                    message: '修改成功。',
                    showClose: true
                });
            }else{
                Message({
                    type: 'error',
                    message: '修改失败,请重试。',
                    showClose: true
                });
            }
        },
    }
}

export default user